const app = getApp();
Page({

  data: {
    authLocationTips: false,
    addressName: '恒大雅苑',
    areaInfo_name: [], //选中地区名称
    area_id_Info: [], //选中的地区id信息
    input_val: '', //查询详细地址
    ch_latitude: '', //当前
    ch_longitude: '', //当前
    do_type: 2, //2添加 1编辑
    v_id: '',
    villageType: [], //园区类型列表
    villageIndex: '', //选中的类型下标
    onlineThrashTemplateTitle: '平台默认模板',
    customRechargeTemplateTitle: '平台默认模板',
    date: '',
    dateSwitch: false, //开关
    isProportion: false,
    isThreshold: false,
    proportion: "", //低余额水卡比例提示
    threshold: "",
    areaCodeText: '', //区域码+名称
  },


  onReady: function () {
    this.cascade = this.selectComponent("#cascade");
    this.dateTime = this.selectComponent("#dateTime");
  },

  //打开联动地址组件
  showCascade() {
    this.cascade.selection(this.data.area_id_Info);
  },

  //联动地址组件complete
  cascadeComplete(e) {
    const detail = e.detail;
    this.setData({
      areaInfo_name: detail.names,
      area_id_Info: detail.ids
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.from = options.from || '';
    var that = this;
    wx.showLoading();
    if (options.type == 1) {
      // 编辑
      wx.setNavigationBarTitle({
        title: '园区编辑'
      });
      that.setData({
        v_id: options.v_id
      });
    } else if (options.type == 2) {
      that.sell_id = 0;
      that.template_id = 0;
      let d = new Date();
      let date = `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`
      that.setData({
        addressName: '',
        date
      });
      // 添加
      wx.setNavigationBarTitle({
        title: '园区添加'
      })
    }
    that.setData({
      do_type: options.type
    });
    that.getVillageType();
  },




  //获取园区类型
  getVillageType() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getVillageType',
      method: "POST",
      data: {},
      success: function (res) {
        var flag = res.data;
        if (flag.code > 0) {
          var json = flag.data;
          var temp = Object.keys(json).map((item, index) => ({
            key: item,
            value: json[item]
          }));
          that.setData({
            villageType: temp
          })
          if (that.data.do_type == 1) {
            that.getVillage();
          } else {
            wx.hideLoading();
          }
        }
      }
    })
  },
  changeSwitch(e) {
    const value = e.detail.value;
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: value
    })
  },

  handleProportionInput(e) {
    let value = e.detail.value;
    if (value > 100) {
      app.showToast("超出百分比最大值");
      value = 100;
    }
    this.setData({
      proportion: value
    });
  },

  handleThresholdInput(e) {
    this.setData({
      threshold: e.detail.value
    })
  },



  //跳转到设置区域码中间页面
  navMiddleAreaCode() {
    let _self = this;
    wx.navigateTo({
      events: {
        acceptDataFromMiddleAreaCode: function (data) {
          if (data) {
            _self.setModal(data);
          }
        }
      },
      url: '../middle/areaCode/index?type=2',
      success: function (res) {
        res.eventChannel.emit("acceptDataFromOpenerPage", {
          area_code_id: _self.area_code_id
        })
      },
    })
  },

  setTemplate(results) {
    if (this.currentType == 1) {
      this.setData({
        onlineThrashTemplateTitle: results.data.template_title,
      })
      this.sell_id = results.template_id;
    } else {
      this.setData({
        customRechargeTemplateTitle: results.data.template_title,
      })
      this.template_id = results.template_id;
    }
  },

  navMiddleTemplate(e) {
    let _self = this;
    const type = e.currentTarget.dataset.type;
    this.currentType = type;
    wx.navigateTo({
      events: {
        acceptDataFromMiddleTemplate: function (data) {
          if (data) {
            if (type == 1) {
              _self.setData({
                onlineThrashTemplateTitle: data.template_title,
              })
              _self.sell_id = data.id;
            } else {
              _self.setData({
                customRechargeTemplateTitle: data.template_title
              })
              _self.template_id = data.id;
            }
          }
        },
      },
      url: '../middle/template/index?type=' + type,
      success: function (res) {
        res.eventChannel.emit("acceptDataFromOpenerPage", {
          template_id: type == 1 ? _self.sell_id : _self.template_id
        })
      },
    })
  },



  setModal(data) {
    console.log("收到的数据", data);
    this.area_code_id = data.id; //区域码id
    this.setData({
      areaCodeText: `${data.name}(${data.area_code})`
    })
  },


  //选择园区类型
  villageTypeChange(e) {
    this.setData({
      villageIndex: e.detail.value
    })
  },

  input_village: function (e) {
    this.setData({
      addressName: e.detail.value
    });
  },


  //打开日期组件
  showDateTime() {
    this.dateTime.show();
  },


  //修改日期组件数据
  changeDate(e) {
    this.setData({
      date: e.detail.result
    })
  },



  //switch选择
  limitTime(e) {
    this.setData({
      dateSwitch: !this.data.dateSwitch
    })
  },


  navMapSetting() {
    wx.getSetting({
      success: settingRes => {
        if (settingRes.errMsg === "getSetting:ok") {
          const setting = settingRes.authSetting;
          if (setting["scope.userLocation"] == undefined || setting["scope.userLocation"]) {
            if (!this.data.ch_latitude || !this.data.ch_longitude) {
              wx.getLocation({
                type:"gcj02",
                success: results => {
                  this.setData({
                    ch_latitude: results.latitude,
                    ch_longitude: results.longitude
                  })
                  this.openLocation();
                },
                fail: res => {
                  app.showToast("请检查是否打开手机定位功能");
                }
              })
            } else {
              this.openLocation();
            }

          } else if (setting["scope.userLocation"] == false) {
            this.setData({
              authLocationTips: true
            })
          }
        }
      },
      fail: e => {
        app.showToast("getSetting fail");
      }
    })
  },

  openLocation() {
    console.log("ch_latitude", this.data.ch_latitude - 0, "ch_longitude", this.data.ch_longitude - 0)
    wx.chooseLocation({
      latitude: this.data.ch_latitude - 0,
      longitude: this.data.ch_longitude - 0,
      success: res => {
        if (res.errMsg === "chooseLocation:ok") {
          this.setData({
            input_val: res.name,
            ch_longitude: res.longitude,
            ch_latitude: res.latitude
          })
        }
        console.log(res, "results")
      },
      fail: e => {
        if (e.errMsg === "chooseLocation:fail auth deny") {
          this.setData({
            authLocationTips: true
          })
        }
      }
    })
  },

  handleOpenSetting() {
    wx.openSetting({
      success: res => {
        if (res.errMsg === "openSetting:ok") {
          if (res.authSetting["scope.userLocation"]) {
            this.setData({
              authLocationTips: false
            })
            this.openLocation()
          }
        }
      },
      fail: e => {
        app.showToast("打开设置失败");
      }
    })
  },


  closeLocationTips() {
    this.setData({
      authLocationTips: false
    })
  },


  //园区地址
  bindKeyInput(e) {
    this.setData({
      input_val: e.detail.value
    })
  },


  confirmBtn() {

    let village_name = this.data.addressName;
    if (village_name == "") {
      app.showToast("请输入园区名称");
      return false;
    }
    let villageIndex = this.data.villageIndex;
    if (villageIndex === "") {
      app.showToast("请选择园区类型");
      return false;
    }
    const areaInfo_name = this.data.areaInfo_name;
    const area_id_Info = this.data.area_id_Info;
    if (areaInfo_name.length == 0) {
      app.showToast("请选择园区地址");
      return false;
    }
    let address = this.data.input_val;
    if (address == "") {
      app.showToast("请定位详细地址");
      return false;
    }
    const data = {
      village_name,
      village_type: this.data.villageType[villageIndex].key,
      province: area_id_Info[0],
      city: area_id_Info[1],
      area: area_id_Info[2],
      province_name: areaInfo_name[0],
      city_name: areaInfo_name[1],
      area_name: areaInfo_name[2],
      address,
      lat: this.data.ch_latitude,
      lng: this.data.ch_longitude,
    }
    let do_type = this.data.do_type,
      url;
    if (do_type == 1) {
      url = "Partner/Village/editVillage";
      data.id = this.data.v_id;
    } else if (do_type == 2) {
      url = "Partner/Village/addVillage";
      Object.assign(data, {
        check_card_record: this.data.dateSwitch == true ? 1 : 2,
        check_record_card_time: this.data.dateSwitch == true ? this.data.date : "",
        template_id: this.template_id,
        set_template_id: this.sell_id,
        area_code_id: this.area_code_id || '',
        prompt_on: this.data.isProportion ? 1 : 2,
        prompt_value: this.data.isProportion ? this.data.proportion : '',
        threshold_on: this.data.isThreshold ? 1 : 2,
        threshold_value: this.data.threshold,
      });
    }
    wx.showLoading({
      mask: true
    })
    app.ajax({
      url,
      data,
      success: res => {
        wx.hideLoading();
        if (res.data.code > 0) {
          app.showToast(res.data.message, "success");
          if (this.from == 'middle') {
            console.log(res.data.data, "res.data.data")
            let results = res.data.data;
            const pages = getCurrentPages();
            let page = pages[pages.length - 3];
            let village = {
              id: results.village_id,
              ...results.data
            }

            page.setData({
              village,
              longitude: results.data.lng,
              latitude: results.data.lat,
              address: results.data.address
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 2,
              })
            }, 1500)
          } else {
            this.navgiateBackAndUpdateList();
          }
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误");
      }
    });
  },


  //编辑时，获取园区信息
  getVillage() {
    var that = this;
    if (that.data.v_id.length == 0) {
      app.showToast('请选择园区');
      setTimeout(function () {
        wx.redirectTo({
          url: '../community/community'
        })
      }, 2000);
      return false;
    }
    app.ajax({
      url: 'Partner/Village/getVillage',
      method: "POST",
      data: {
        id: that.data.v_id
      },
      success: function (res) {
        var flag = res.data;
        wx.hideLoading();
        if (flag.code > 0) {
          //园区类型
          if (that.data.villageType.length > 0) {
            that.data.villageType.forEach((item, index) => {
              if (item.key == flag.data.village_type) {
                that.setData({
                  villageIndex: index
                })
              }
            })
          }
          const areaInfo_name = [flag.data.province_name, flag.data.city_name, flag.data.area_name];
          const area_id_Info = [flag.data.province, flag.data.city, flag.data.area];
          that.setData({
            addressName: flag.data.village_name,
            areaInfo_name,
            area_id_Info,
            input_val: flag.data.address,
            ch_latitude: flag.data.lat,
            ch_longitude: flag.data.lng
          });
        } else {
          app.showToast(flag.message);
          return false;
        }
      }
    })
  },


  //返回上一页并更新数据  返回community
  navgiateBackAndUpdateList() {
    setTimeout(() => {
      const pages = getCurrentPages();
      if (pages.length >= 2) {
        const targetPage = pages[pages.length - 2];
        targetPage.reloadData();
      }
      wx.navigateBack({
        complete: (res) => {},
      })
    }, 2000)
  }

})